/*
 * Create:      柿子
 * CreateDate:  2022/12/14
 * Describe：   门诊病历信息（新范例病例样式）
 * */
import React from 'react';
import {
	Tree, Input, Icon, Modal, message, Popconfirm, Spin
} from 'antd';
import { Util } from 'tools/index';
import { Keup } from '../../../tools/index';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import store from 'store';
import '../../pharmacy/outpha/style/outpha.less';
import '../style/CMOrderSave.less';

import AddSampleTemplate from './AddSampleTemplate.jsx'; // 保存范例病历
import CaseInformationPageTabs from './CaseInformationPageTabs.jsx';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import MedicalRecordTemplateSelection from './MedicalRecordTemplateSelection.jsx'; // 加载病历模板

const { TreeNode } = Tree;
const { confirm } = Modal;
let timer = null;

class CaseInformationPage extends React.Component {
	constructor(props) {
		super(props)
		var userData = React.$getSessionData();
		var recordData = React.$getSessionData('patientData');
		var titleData = React.$getSessionData('titleData');
		this.state = {
			recordData,
			userData,
			titleData,
			expandedKeys: [],
			selectedKeys: [],
			treeSelectData: {},
			treeData: [],
			templateName: '',
			autoExpandParent: true,
			modalTemplateData: [],
			oldModalTemplateData: [],
			modalRowData: {},
			isVResize: false,
			hNum: 100,
			vNum: 920,
			hNumLimit: 30,
			vNumLimit: 30,
			savedTemplatesData: [], // 已保存模板
			tableData: [],
			columns: [],
			total: 0,
			page: 1,
			pageSize: 10,
			loading: false,
			showValidateResult: 'show', // 是否显示错误下拉框
			templateValue: undefined,
			historyAdmID: '',
			spinLoading: false,
			loadingTitle: '',
			defaultMillisecond: 0, // 默认倒计时毫秒数
			isDeleteRecord: false, // 是否可以删除病历
			isUnlocking: true,
			templateParams: []
		}
		this.resizeOffsetInfo = {
			clientTop: 0,
			clientLeft: 0
		}

		this.leftHeight = 0

		this.containerWidth = 0
	}

	componentDidMount() {
		let _this = this;
		this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
		this.initResizeInfo();
		this.getChineseAndEnglishData();
		this.props && this.props.onRef && this.props.onRef(this);

		window.onresize = function () {
			setTimeout(function () {
				_this.initResizeInfo()
			}, 200);
		}
		this.getTreeData();
		this.insty() // 录入权限
	}

	static getDerivedStateFromProps(nextProps, prevState) {
		//该方法内禁止访问this
		if (nextProps.historyAdmID !== prevState.historyAdmID) {
			//通过对比nextProps和prevState，返回一个用于更新状态的对象
			return true
		}
		//不需要更新状态，返回null
		return null
	}

	componentDidUpdate() {
		// 做一些需要this.props的事
		if (this.props.historyAdmID && (this.props.historyAdmID !== this.state.historyAdmID) && this.props.isDidUpdate && this.props.isDidUpdate === 'Y') {
			this.setState({ historyAdmID: this.props.historyAdmID }, () => {
				this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
				// this.getSavedTemplatesData(); // 查询已保存病历列表
				this.getTreeData();
				this.insty() // 录入权限
			})
		}
	}

	componentWillUnmount() {
		this.handleClearComponentInformation();
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => { return; }
	}

	// 切换病人更新相关数据
	loadPatientMsg = () => {
		this.setState({
			recordData: React.$getSessionData('patientData'),
			titleData: React.$getSessionData('titleData'),
		}, () => {
			this.getDefaultTemplate(); // 设置默认模板
			this.getTreeData();
			this.insty() // 录入权限
		})
	}

	// 组件销毁时清除组件信息
	handleClearComponentInformation = () => {
		let { treeSelectData, modalRowData, selectedKeys, defaultMillisecond, recordData } = this.state;
		if (this.state.eMRRecordID && this.props.isOperable !== 'Y') {
			this.jqAjax(this.state.eMRRecordID, (res) => {
				console.log(res)
			}) // 成功的回调
		}
		window.onresize = null;
		window.sessionStorage.setItem('showMessagePopUp', 'Y');
		window.sessionStorage.setItem('outEMRDefaultTemplate', JSON.stringify({
			treeSelectData,
			modalRowData,
			selectedKeys,
			defaultMillisecond,
			admID: recordData && recordData.admID ? recordData.admID : ''
		})); // 保存当前加载的病历模板
		if (timer) {
			clearInterval(timer);
		}
	}

	// 同步请求 -- 解锁
	jqAjax = (eMRRecordID, success, error) => {
		if ($ && $.ajax) {
			let userData = React.$getSessionData();
			if (!(eMRRecordID && userData && userData.userID)) {
				return;
			}
			let url = httpConfig.ipDeault + httpConfig.urlAddress;
			let json = {
				params: [{
					patEMRRecordID: eMRRecordID,
				}]
			}
			let formData = Object.assign({}, json);
			let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
			windowHost = windowHost + '/bdhealth/';
			// 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
			url = windowHost && windowHost.indexOf('localhost') !== -1 ? url : windowHost;
			formData.code = '06050015';
			if (userData) {
				let ip = React.$getSessionData('ipConfig');
				formData.session = [{
					'userID': userData.userID || '',
					'locID': userData.locID || '',
					'groupID': userData.groupID || '',
					'hospID': userData.hospID || '',
					'sessionID': userData.sessionID || '',
					'hostName': ip?.hostName || '',
					'ipv4': ip?.ipv4 || '',
					'ipv6': ip?.ipv6 || '',
					'mac': ip?.mac || '',
				}]
			}
			$.ajax({
				type: 'post',                          //请求方式
				url,     //请求地址
				data: JSON.stringify(formData),                         //发送的数据，这里是json对象
				dataType: 'json',                      //数据类型
				// contentType: 'application/json;charset=utf-8',
				async: false,
				success: function (data) {
					success && success(data);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					// console.log(XMLHttpRequest, textStatus, errorThrown)
					error && error(errorThrown);
				},
				headers: {
					'Accept': 'application/json',
					'Content-Type': 'application/json',
					'Authorization': httpConfig.authorizationToken,
					'Access-Control-Allow-Origin': httpConfig.ipDeault
				},
			});
		}
	}

	insty = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''), // 就诊记录主键
			}]
		}
		$http.post('urlDeault', this, {
			code: '03040038',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					if (res.hasDocFlag != 'Y') {
						let messageTime = this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3;
						Keup.ModalMessage(messageTime, this, '未分配主管医师，禁止录入!', '自动关闭', 'destroy', '确定', 'error')
					}
				}
			}
		})
	}

	// 获取中英文数据
	getChineseAndEnglishData = () => {
		let { userData } = this.state;
		let data = {
			params: [{
				compontName: 'CaseInformationPage',
				type: 'C',
				reactCode: ['CaseInformationPage']
			}]
		}
		$http.post('urlDeault', this, {
			code: '01040073',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					var totalWidth = 0;
					let arr = res.result.C && res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							widthNum: parseInt(item.width),
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					let obj = {
						title: userData.language == 'EN' ? 'Operation' : '操作',
						key: 14,
						align: 'center',
						width: '80px',
						fixed: 'right',
						widthNum: 80,
						render: (text, record) => (
							<span>
								<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
								<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
									<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
								</Popconfirm>
							</span>
						),
					};
					filterArr.push(obj);
					for (var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
					}
					this.setState({
						columns: filterArr,
						totalWidth,
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
					})
				}
			}
		})
	}

	onMainColumnRef = ref => {
		this.mainColumnRef = ref;
	}

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
	}

	handleDelete = record => {
		console.log(record)
	}

	// 获取板分组科室下默认模板
	getDefaultTemplate = () => {
		let { recordData, userData } = this.state;
		let defaultTemplate = sessionStorage.getItem('outEMRDefaultTemplate') && JSON.parse(sessionStorage.getItem('outEMRDefaultTemplate'));
		if (defaultTemplate && defaultTemplate.admID && (defaultTemplate.admID === recordData?.admID)) {
			this.setState({ ...defaultTemplate, spinLoading: true, loadingTitle: '病历模板加载中……' }, () => {
				this.handleLoadingMedicalRecords(defaultTemplate?.treeSelectData, defaultTemplate?.modalRowData, defaultTemplate?.modalRowData?.flag || '');
			})
		} else {
			let data = {
				params: [{
					admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
					admLanguage: userData && userData.admLanguage ? userData.admLanguage : 'CN',
				}]
			}
			$http.post('urlS', this, {
				code: '06010094',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						let dataAry = res.result.dataAry;
						let defaultMillisecond = res.result && res.result.autoSaveTime ? Number(res.result.autoSaveTime) : 0;
						if (!(dataAry && dataAry.length > 0)) {
							this.setState({ defaultMillisecond })
							return;
						}
						let key = [];
						let treeSelectData = JSON.parse(JSON.stringify(dataAry[0]));
						treeSelectData.ID = treeSelectData.wTemplateCatID;
						if (treeSelectData && 'patEMRRecordID' in treeSelectData && treeSelectData.patEMRRecordID) {
							key.push(treeSelectData.patEMRRecordID);
						} else {
							key.push(treeSelectData.wTemplateCatID);
						}
						this.setState({ selectedKeys: key, defaultMillisecond, spinLoading: true, loadingTitle: '病历模板加载中……' }, () => {
							let obj = JSON.parse(JSON.stringify(dataAry[0]));
							obj.ID = obj.templateID;
							obj.releaseVersion = obj.eMRReleaseVersion; // 版本号
							if (obj && 'patEMRRecordID' in obj && obj.patEMRRecordID) {
								obj.flag = 'patientRecords';
								this.handleLoadingMedicalRecords(treeSelectData, obj, 'patientRecords');
							} else {
								this.setState({ modalRowData: obj }, () => { // 加载病历模板
									this.getModalTemplateData(treeSelectData, "default");
								})
							}
						})
					}
				}
			})
		}
	}

	// 处理tree数据
	filterTreeData = (treeData, type) => {
		let data = treeData && treeData.map(item => {
			// 当为首程并且首程下存在病程时则首程的progressID就为病程ID;
			let progressID = item && item.subCatalog && item.subCatalog.length > 0 && item.subCatalog[0].treeType && item.subCatalog[0].treeType === 'PROGRESS' ? 'first' : '';
			return {
				title: item.descripts,
				key: item.ID,
				treeType: item && item.treeType ? item.treeType : (item && item.subCatalog ? 'CATALOG' : 'TEMPLATE'),
				progressID: item && item.treeType && item.treeType === 'PROGRESS' ? item.ID : progressID,
				...item,
				children: this.filterTreeData(item.subCatalog, type)
			}
		});
		return data;
	}

	// 3.6.1.根据患者获取病历模板分组目录树
	getTreeData = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
				wTempVer: 'Y', // 是否查询导航目录模板版本信息
				patEMRRec: 'Y', // 是否查询患者已填写病历信息
				locID: this.props && this.props.locID ? this.props.locID : '', // 患者病历预览界面专用 -- 科室ID
				fGroup: this.props && this.props.fGroup ? this.props.fGroup : '', // 患者病历预览界面专用 -- 职能科室
				fGroupTempByInfo: this.props && this.props.fGroupTempByInfo ? this.props.fGroupTempByInfo : '', // 患者病历预览界面专用
			}]
		}
		$http.post('urlS', this, {
			code: '06050006',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result);
					this.setState({ treeData: arr }, () => {
						this.generateList(this.state.treeData);
					})
				} else {
					this.setState({ treeData: [] });
				}
			}
		})
	}

	renderTreeNodes = data => data.map((item) => {
		const index = item.title.indexOf(this.state.templateName);
		const beforeStr = item.title.substr(0, index);
		const afterStr = item.title.substr(index + this.state.templateName.length);
		const title = index > -1 ? (
			<span>
				{beforeStr}
				<span style={{ color: '#FF7F00' }}>{this.state.templateName}</span>
				{afterStr}
			</span>
		) : <span>{item.title}</span>;
		let type = item.treeType === 'CATALOG' ? 'folder-open' : ((item.treeType === 'TEMPLATE' && !(item.progressID && item.progressID !== 'first')) ? 'folder' : 'file');
		if (item.children) {
			return (
				<TreeNode icon={<Icon type={type} />} title={<span onClick={() => this.handleAnchorPositioning(item)}>{title}</span>} key={item.key} dataRef={item}>
					{this.renderTreeNodes(item.children)}
				</TreeNode>
			);
		}
		return <TreeNode icon={<Icon type={type} />} title={<span onClick={() => this.handleAnchorPositioning(item)}>{title}</span>} key={item.key} dataRef={item} />;
	})

	// 锚点定位
	handleAnchorPositioning = item => {
		let recordID = 'record' + item.ID;
		if (item && item.treeType === 'PROGRESS') {
			this.caseTemplateChild && this.caseTemplateChild.handleAnchorPositioning(recordID);
		}
	}

	getParentKey = (key, tree) => {
		let parentKey;
		for (let i = 0; i < tree.length; i++) {
			const node = tree[i];
			if (node.children) {
				if (node.children.some(item => item.key === key)) {
					parentKey = node.key;
				} else if (this.getParentKey(key, node.children)) {
					parentKey = this.getParentKey(key, node.children);
				}
			}
		}
		return parentKey;
	};

	//以下是Tree展开搜索
	dataList = [];
	generateList = (data) => {
		for (let i = 0; i < data.length; i++) {
			const node = data[i];
			const key = node.key;
			this.dataList.push({ key, title: node.title });

			if (node.children) {
				this.generateList(node.children);
			}
		}
		// 默认进来tree全部加载
		const expandedKeys = this.dataList.map((item) => {
			return this.getParentKey(item.key, this.state.treeData);
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			expandedKeys,
		});
	};

	handleTemplateNameChange = e => {
		const templateName = e.target.value;
		const expandedKeys = this.dataList.map((item) => {
			if (templateName.length === 0) return null;
			if (item.title.indexOf(templateName) > -1) {
				return this.getParentKey(item.key, this.state.treeData);
			}
			return null;
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			expandedKeys,
			templateName: e.target.value,
			autoExpandParent: true,
		});
	}

	onExpand = (expandedKeys) => {
		this.setState({
			expandedKeys,
			autoExpandParent: false,
		});
	}

	// 病历模板树选中操作
	onSelect = (keys, event) => {
		let { spinLoading } = this.state;
		let selectData = event.node.props.dataRef;
		let treeSelectData = JSON.parse(JSON.stringify(selectData));
		if (!(keys && keys.length > 0)) {
			return;
		}
		if ((selectData && !(selectData.treeType === 'TEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
			return;
		}
		// let selectedKeys = []; // 关联选中病历模板
		// selectedKeys.push(treeSelectData.wTempCataID);
		this.setState({ selectedKeys: keys }, () => {
			treeSelectData.ID = treeSelectData.wTempCataID;
			selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
			if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && selectData.treeType === 'TEMPLATE') {
				this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords');
			} else if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && selectData.treeType === 'CATALOG' && selectData.parentID) {
				this.getModalTemplateData(selectData);
			}
		})
	}

	dblclickTreeNodes = (status, record) => {
		let { spinLoading } = this.state;
		let selectData = record.props.dataRef;
		if ((selectData && !(selectData.treeType === 'TEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
			return;
		}
		let treeSelectData = JSON.parse(JSON.stringify(selectData));
		let ID = selectData && selectData.ID ? selectData.ID : '';
		let key = [];
		key.push(ID);
		this.setState({ selectedKeys: key }, () => {
			treeSelectData.ID = treeSelectData.wTempCataID;
			selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
			if (selectData && selectData.treeType === 'TEMPLATE') {
				this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords');
			} else if (selectData && selectData.treeType === 'CATALOG') {
				this.getModalTemplateData(selectData);
			}
		})
	}

	handleOk = (record) => {
		let falg = 'sampleDirectory'
		if (JSON.stringify(record) == '{}') {
			record = { ...this.state.treeSelectData };
			let modalRowData = { ...this.state.treeSelectData };
			falg = modalRowData?.flag || falg;
		}
		record.isHanle = this.state.isHanle;
		let treeSelectData = JSON.parse(JSON.stringify(record));
		treeSelectData.ID = treeSelectData.wTempCataID;
		this.getPatienHistoryData(treeSelectData, record, falg);
	}

	handleCancel = () => {
		this.setState({ spinLoading: false });
	}

	// 3.6.2.根据分组目录获取模板
	getModalTemplateData = Util.debounce((treeSelectData, isHanle) => {
		let { modalRowData, recordData } = this.state;
		let data = {
			params: [{
				groupTemplateID: treeSelectData.ID, // 分组目录ID - 导航目录ID
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
				locID: this.props && this.props.locID ? this.props.locID : '', // 患者病历预览界面专用 -- 科室ID
				fGroup: this.props && this.props.fGroup ? this.props.fGroup : '', // 患者病历预览界面专用 -- 职能科室
				fGroupTempByInfo: this.props && this.props.fGroupTempByInfo ? this.props.fGroupTempByInfo : '', // 患者病历预览界面专用
			}]
		}
		$http.post('urlS', this, {
			code: '06050007',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					for (var i = 0; i < res.result.length; i++) {
						if (res.result[i].ID === modalRowData.ID) {
							res.result[i].checked = true;
							modalRowData = res.result[i];
							break;
						}
					}
					let modalTemplateData = res.result.filter(function (item) { return item.releaseVersion });
					// let prSelectedKeys = []; // 患者病历选中操作
					// prSelectedKeys.push(modalRowData.ID)
					this.setState({ modalTemplateData, oldModalTemplateData: modalTemplateData, isHanle: isHanle ? isHanle : '' }, () => {
						if (this.state.isHanle !== 'default') {
							// if (this.state.modalTemplateData && this.state.modalTemplateData.length > 1) {
							// 	// this.showModal();
							// } else {
							// 	// 获取患者病历数据
							// 	let obj = this.state.modalTemplateData && this.state.modalTemplateData.length > 0 ? this.state.modalTemplateData[0] : {};
							// 	this.getPatienHistoryData(treeSelectData, obj, 'loadTemplate')
							// }
							this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(true, treeSelectData, this.state.modalTemplateData);
						} else {
							this.setState({ modalRowData }, () => {
								this.getPatienHistoryData(treeSelectData, { ...modalRowData, isHanle }, 'loadTemplate')
							})
						}
					})
				} else {
					this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false })
				}
			},
			error: function () {
				this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false })
			}
		})
	})

	// 判断文件内容是否修改
	getModified = () => {
		let isModify = this.caseTemplateChild && this.caseTemplateChild.getModified ? this.caseTemplateChild.getModified() : false;
		return isModify
	}

	// 3.6.8.获取患者病历数据
	getPatienHistoryData = Util.debounce((treeSelectData, obj, flag) => {
		let oldModalRowData = this.state.modalRowData && this.state.modalRowData.ID ? JSON.parse(JSON.stringify(this.state.modalRowData)) : obj; // 历史选择的模板数据
		let isModify = this.getModified();
		let _this = this;
		if (obj.isHanle !== 'default' && isModify) {
			confirm({
				title: <div>当前病历 <span style={{ fontWeight: '900' }}>{oldModalRowData.descripts}</span> 已修改，是否需要保存？</div>,
				okText: '是->保存',
				cancelText: '否->无需保存',
				onOk() {
					obj.load = true; // 是否加载切换的病历模板
					obj.flag = flag;
					obj.saveType = 'auto';
					_this.setState({ spinLoading: true, loadingTitle: '保存中……' }, () => {
						_this.handleSave(treeSelectData, obj);
					})
				},
				onCancel() {
					_this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
				},
			});

			if (flag === 'cancel') {
				this.handleCancel();
			}
		} else {
			_this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
		}
	})

	// 加载病历
	newLoadingMedicalRecords = (treeSelectData, obj, flag) => {
		let { recordData, titleData } = this.state;
		let data = {
			params: [{
				patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
				// catalogueID: treeSelectData.ID, // 分组目录ID
				// groupTemplateID: obj.ID, // 分组模板ID
				power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
			}]
		}
		$http.post('urlS', this, {
			code: '06050008',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log(res.result) // eMRRecordID 
					let authority = res.result && res.result.authority ? res.result.authority : {};
					let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
					// let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
					obj.flag = flag; // 保存调用类型
					obj.removeLockFlag = authority.removeLockFlag;
					let needUpdateData = res.result && res.result.needUpdateData && res.result.needUpdateData.length ? res.result.needUpdateData : [];
					for (var i = 0; i < needUpdateData.length; i++) {
						needUpdateData[i].key = i + 1;
					}
					let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
					let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
					let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID, needUpdateData];
					this.setState({ // recordDataID -- 病历记录数据ID
						templatePath: res.result && res.result.templatePath ? res.result.templatePath : '', eMRRecordID: res.result.eMRRecordID, treeSelectData, templateParams,
						modalRowData: obj, spinLoading: false, isUnlocking: this.props.isOperable === 'Y' ? true : false, recordDataID: res.result && res.result.recordDataID ? res.result.recordDataID : ''
					}, () => {
						this.state.templatePath ? this.caseTemplateChild?.setElementTextByID(...templateParams) : this.caseTemplateChild?.NewFile();
						if (flag === 'cancel') {
							this.handleCancel();
						}
						authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
					})
				} else {
					this.setState({ patienHistoryData: [], spinLoading: false })
				}
			},
			error: function () {
				this.setState({ patienHistoryData: [], spinLoading: false })
			}
		})
	}

	handleCaseTemplateRef = ref => {
		this.caseTemplateChild = ref
	}

	// 病历加载
	handleLoadingMedicalRecords = (treeSelectData, obj, flag) => {
		this.setState({ spinLoading: true, loadingTitle: '病历加载中……' }, () => {
			if (flag === 'patientRecords') {
				this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
					this.newLoadingMedicalRecords(treeSelectData, obj, flag);
				})
			} else {
				this.SaveMedicalRecord(treeSelectData, obj, flag)
			}
		})
	}

	// 3.6.3.保存病历记录
	SaveMedicalRecord = Util.debounce((treeSelectData, obj, flag, selectionXml) => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
				cataLogID: treeSelectData.ID, // 分组模板目录ID
				seqNo: '',
				templateID: obj.ID, // 病历模板ID
				sPatRecPower: flag === 'courseOfDisease' ? 'saveEMRProgress' : undefined
			}]
		}
		$http.post('urlS', this, {
			code: '06050001',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let recordID = res && res.ID ? res.ID : '';
					obj.BSEMRRDParRef = recordID;
					if (flag === 'courseOfDisease') {
						this.caseTemplateChild && this.caseTemplateChild.insertTheCourseOfDisease && this.caseTemplateChild.insertTheCourseOfDisease(selectionXml, recordID, obj)
					} else if (flag === 'sampleDirectory') { // 加载范例病历
						this.setState({ isDeleteRecord: false }, () => {
							this.handleLoadSampleMedicalRecord(treeSelectData, obj, flag)
						})
					} else if (flag === 'loadTemplate' || flag === 'cancel') { // 加载病历模板
						this.setState({ isDeleteRecord: false }, () => { // 加载的病历模板不能删除
							this.handleLoadingMedicalRecordTemplate(treeSelectData, obj, flag)
						})
					} else {
						this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
							this.newLoadingMedicalRecords(treeSelectData, obj, flag);
						})
					}
				} else {
					this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading();
					this.setState({ spinLoading: false });
				}
			},
			error: function () {
				this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading();
				this.setState({ spinLoading: false });
			}
		})
	})

	// 加载范例病例
	handleLoadSampleMedicalRecord = async (treeSelectData, obj, flag) => {
		try {
			let { recordData, titleData } = this.state;
			let data = {
				params: [{
					// obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID
					patEMRRecordID: '',
					admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
					groupTemplateID: obj.ID, // 分组模板ID
					power: this.props.medicalType == 'Z' ? 'OutHospRecord' : '',
					examTempID: treeSelectData?.examTempID || ''
				}]
			}
			let res = await React.$asyncPost(this, '06050106', data);
			let authority = res.result && res.result.authority ? res.result.authority : {};
			let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
			obj.flag = flag; // 保存调用类型
			obj.removeLockFlag = authority.removeLockFlag;
			let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
			let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID;
			let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
			let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID];
			this.setState({
				templatePath, eMRRecordID, treeSelectData, templateParams,
				modalRowData: obj, spinLoading: false, isUnlocking: true
			}, () => {
				this.state.templatePath ? this.caseTemplateChild?.setElementTextByID(...templateParams) :
					this.caseTemplateChild?.NewFile();
				this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(false);
				authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
			})
		} catch (error) {
			console.log(error);
			this.setState({ spinLoading: false });
		}
	}

	// 加载病历模板
	handleLoadingMedicalRecordTemplate = (treeSelectData, obj, flag) => {
		let { recordData, titleData } = this.state;
		let data = {
			params: [{
				patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
				groupTemplateID: obj.ID, // 分组模板ID
				power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
			}]
		}
		$http.post('urlS', this, {
			code: '06050016',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let authority = res.result && res.result.authority ? res.result.authority : {};
					let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
					// let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
					obj.flag = flag; // 保存调用类型
					obj.removeLockFlag = authority.removeLockFlag;
					let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
					let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
					let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID];
					this.setState({
						templatePath, eMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID, treeSelectData,
						modalRowData: obj, spinLoading: false, isUnlocking: true, templateParams
					}, () => {
						this.state.templatePath ? this.caseTemplateChild.setElementTextByID(...templateParams) : this.caseTemplateChild?.NewFile();
						if (flag === 'cancel') {
							this.handleCancel();
						}
						authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
					})
				} else {
					this.setState({ patientHistoryData: [], spinLoading: false })
				}
			},
			error: function () {
				this.setState({ patientHistoryData: [], spinLoading: false })
			}
		})
	}

	// 3.6.5.保存患者病历数据
	savePatientMedicalRecord = (newWTreeSelectData, record, fn) => {
		let { modalRowData, treeSelectData, titleData } = this.state;
		let oldTreeSelectData = JSON.parse(JSON.stringify(treeSelectData));
		let templateData = this.caseTemplateChild.getTemplateXml('form');
		let data = {
			params: [{
				queID: this.props.editorID === 'OSEWriterControl' ? (titleData?.queID || '') : undefined, // 队列ID
				areaRoomID: this.props.editorID === 'OSEWriterControl' ? (titleData?.areaRoomID || '') : undefined, // 诊室ID
				BSEMRRDParRef: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
				recordData: templateData && templateData.xmlStr ? templateData.xmlStr : '', // 病历记录数据 --- 模板xml
				progressRecIDAry: templateData && templateData.allRecordID ? templateData.allRecordID : [], // 病历记录数据 --- 病程记录ID
				progressRecDataSource: templateData?.recordDataSource || [],
				submitOrNot: 'N', // submitOrNot
				auditOrNot: 'N', // 是否审核标志
				lockStatus: 'Y', // 锁定标志
				archivingStatus: 'U', // 归档标志
				wCatalogueID: oldTreeSelectData.ID, // 分组目录ID
				versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : '', // 病历模板ID
				patRecDataSource: this.caseTemplateChild && this.caseTemplateChild.getMedicalRecordFileIDAndValue && this.caseTemplateChild.getMedicalRecordFileIDAndValue(), // 病历所有的输入域以及对应的值
			}]
		}
		// console.log('data', data)
		$http.post('urlS', this, {
			code: '06050004',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ isHanle: '', spinLoading: false, recordDataID: res.result && res.result.recordDataID ? res.result.recordDataID : '' }); // recordDataID -- 病历记录数据ID
					// this.getSavedTemplatesData(); // 获取已保存病历
					this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历
					this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('isModifyPermissions') : ''; // 保存成功后修改编辑状态
					if (newWTreeSelectData === 'handleLoadingMedicalRecordTemplate' || newWTreeSelectData === 'newLoadingMedicalRecords' || newWTreeSelectData === 'handleLoadSampleMedicalRecord') { // 自动保存
						return;
					} // BSEMRRDParRef
					let key = [];
					key.push(modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID);
					// this.setState({ prSelectedKeys: key }, () => {
					this.setState({ isDeleteRecord: true }); // 保存之后可以删除
					message.success('保存成功', this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3);
					if (newWTreeSelectData && newWTreeSelectData.ID) { // 判断是否自动保存的，
						this.setState({ treeSelectData: oldTreeSelectData });
					} else {
						this.setState({ prSelectedKeys: key })
					}
					if (record && record.load) { // 判断是否保存后需要加载新操作的模板，需要的话传入新模板数据
						this.handleLoadingMedicalRecords(newWTreeSelectData, record, record.flag);
					}
					if (fn) {
						fn();
					}
				} else {
					this.setState({ spinLoading: false });
					this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '';
				}
			},
			error: function () {
				this.setState({ spinLoading: false });
				this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '';
			}
		})
	}

	// 更新患者病历记录锁状态
	updateMedicalRecordLockStatus = Util.debounce((eMRRecordID, treeSelectData, obj, flag) => {
		let userData = React.$getSessionData();
		if (!(eMRRecordID && userData && userData.userID)) {
			if (!eMRRecordID) {
				// message.error('模板加载失败')
			}
			return;
		}
		let data = {
			// lockStatus为Y则为加锁
			params: [{
				patEMRRecordID: eMRRecordID,
				lockStatus: flag === 'patientRecords' ? 'Y' : undefined,
				uEMRRecLockPow: treeSelectData === 'forceUnlock' ? 'removeOtherLock' : undefined, // 强制解锁标志
			}]
		}
		$http.post('urlS', this, {
			code: '06050015',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					if (flag === 'patientRecords') { // 加载患者病历
						this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
							this.newLoadingMedicalRecords(treeSelectData, obj, flag);
						})
					}
					if (treeSelectData === 'forceUnlock') { // 强制解锁
						let { modalRowData } = this.state;
						this.setState({ isDeleteRecord: false }, () => {
							this.getPatienHistoryData(this.state.treeSelectData, modalRowData, modalRowData && modalRowData.flag ? modalRowData.flag : '')
						})
					}
				}
			}
		})
	})

	// 保存
	handleSave = (treeSelectData, record, fn) => {
		if (record && record.saveType === 'auto') { // 自动保存不需要加载loading提示
			this.savePatientMedicalRecord(treeSelectData, record, fn);
		} else {
			this.setState({ spinLoading: true, loadingTitle: '保存中' }, () => {
				// this.SaveMedicalRecord(treeSelectData, record, fn);
				this.savePatientMedicalRecord(treeSelectData, record, fn);
			})
		}

	}

	// 查看历史病历时将右侧宽度调宽
	compileVNum = (status) => {
		this.containerWidth = document.getElementById('v_resize_container').offsetWidth
		if (status === 'default') {
			this.setState({
				vNum: 1000,
				vNumLimit: this.containerWidth - 1000,
				showValidateResult: 'show'
			})
		} else {
			this.setState({
				vNum: this.containerWidth / 2 + 50,
				vNumLimit: this.containerWidth / 2 - 50,
				showValidateResult: 'hidden'
			})
		}
	}

	/**
	 * 初始化resize信息
	 */
	initResizeInfo = () => {
		const hEle = document.getElementById('h_resize_container')
		this.resizeOffsetInfo = this.getEleOffset(hEle)
		this.leftHeight = hEle.offsetHeight
		this.containerWidth = document.getElementById('v_resize_container').offsetWidth

		if (hEle.offsetHeight - this.state.hNum < this.state.hNumLimit) {
			this.setState({
				hNum: hEle.offsetHeight - this.state.hNumLimit
			})
		}
		if (this.containerWidth - this.state.vNum < this.state.vNumLimit) {
			this.setState({
				vNum: this.containerWidth - this.state.vNumLimit,
			})
		}
	}

	/**
	 * 获取元素的偏移信息
	 */
	getEleOffset(ele) {
		var clientTop = ele.offsetTop
		var clientLeft = ele.offsetLeft
		let current = ele.offsetParent
		while (current !== null) {
			clientTop += current.offsetTop
			clientLeft += current.offsetLeft
			current = current.offsetParent
		}
		return {
			clientTop,
			clientLeft,
			height: ele.offsetHeight,
			width: ele.offsetWidth
		}
	}

	// 只要鼠标松开或者离开区域，那么就停止resize
	stopResize = () => {
		this.setState({
			isVResize: false
		})
	}

	// 拖动垂直调整块
	vResizeOver = (e) => {
		const { isVResize, vNum, vNumLimit } = this.state
		if (isVResize && vNum >= vNumLimit && (this.containerWidth - vNum >= vNumLimit)) {
			let newValue = e.clientX - this.resizeOffsetInfo.clientLeft
			if (newValue < vNumLimit) {
				newValue = vNumLimit
			}
			if (newValue > this.containerWidth - vNumLimit) {
				newValue = this.containerWidth - vNumLimit
			}
			this.setState({
				vNum: newValue
			})
		}
	}

	// 开始拖动垂直调整块
	vResizeDown = () => {
		this.setState({
			isVResize: true
		})
	}

	// 拖动水平调整块
	hResizeOver = (e) => {
		const { hNum, hNumLimit } = this.state;
		if (hNum >= hNumLimit && (this.resizeOffsetInfo.height - hNum >= hNumLimit)) {
			let newValue = this.resizeOffsetInfo.clientTop + this.resizeOffsetInfo.height - e.clientY
			if (newValue < hNumLimit) {
				newValue = hNumLimit
			}
			if (newValue > this.resizeOffsetInfo.height - hNumLimit) {
				newValue = this.resizeOffsetInfo.height - hNumLimit
			}
			this.setState({
				hNum: newValue
			})
		}
	}

	// 引用
	handleQuote = (str, quoteArr) => {
		this.caseTemplateChild.Spechars(str, quoteArr)
	}

	// 插入知识库xml
	setKnowledgeBaseXMl = (nodeContent, rowData, fn) => {
		this.caseTemplateChild.InsertXmlString(nodeContent, rowData, fn)
	}

	// 新知识库赋值
	knowledgeBaseAssignment = (filedID, value) => {
		this.caseTemplateChild.knowledgeBaseAssignment(filedID, value);
	}

	handleCaseInformationRef = ref => {
		this.caseInformationChild = ref;
	}

	// 供病历公共组件调用获取知识库数据
	getChildKnowledgeBaseTreeData = (fildId) => {
		// console.log('page', fildId, this.state.modalRowData)
		if (this.state.courseID !== fildId) {// 点击同一个病程则不再调用查询知识库方法
			this.setState({ courseID: fildId }, () => {
				this.caseInformationChild.getKnowledgeBaseTreeData(this.state.courseID, this.state.modalRowData);
			})
		}
	}

	// 获取已保存模板
	getSavedTemplatesData = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''), // 就诊记录主键
			}]
		}
		$http.post('urlS', this, {
			code: '06010096',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = res.result && res.result.dataAry ? JSON.parse(JSON.stringify(res.result.dataAry)) : [];
					for (var i = 0; i < arr.length; i++) {
						arr[i].ID = arr[i].eMRTemplateID;
					}
					this.setState({ savedTemplatesData: arr })
				}
			}
		})
	}

	// 删除患者病历
	deletePatientHistory = (type, courseID) => { // type = removeCourse courseID -- 病程ID 删除病程
		let { eMRRecordID, recordDataID } = this.state;
		let allRecordID = this.caseTemplateChild.getTemplateXml('allRecordID');
		if (!eMRRecordID) {
			message.info('暂不支持删除', this.state.userData && this.state.userData.messageTime);
			return;
		}
		let data = {
			params: [{
				eMRRecordID: type === 'removeCourse' ? courseID : eMRRecordID, // 病历记录主键
				recordDataID: type === 'removeCourse' ? undefined : recordDataID, // 病历记录数据ID
				progressRecIDAry: type === 'removeCourse' ? undefined : (allRecordID && allRecordID.length > 0 ? allRecordID : []), // 病程记录ID
			}]
		}
		$http.post('urlS', this, {
			code: '06010097',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success(res.errorMessage, this.state.userData && this.state.userData.messageTime);
					this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历
					if (type !== 'removeCourse') {
						this.setState({ eMRRecordID: '', isDeleteRecord: false, recordDataID: '', isUnlocking: true }); // 置空可删除ID
						// this.getSavedTemplatesData();
						this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('noSave') : ''; // 保存成功后修改编辑状态
						if (timer) { // 清除定时保存的定时器
							clearInterval(timer);
						}
					}
				}
			}
		})
	}

	// 双击加载已保存模板
	handleSaveDTemplatesClick = (item) => {
		let key = [];
		let treeSelectData = JSON.parse(JSON.stringify(item));
		treeSelectData.ID = treeSelectData.wTemplateCatID;
		key.push(treeSelectData.eMRTemplateID);
		this.setState({ selectedKeys: key, treeSelectData }, () => {
			let obj = JSON.parse(JSON.stringify(item));
			obj.ID = obj.eMRTemplateID;
			obj.releaseVersion = obj.eMRReleaseVersion, // 版本号
				setTimeout(() => {
					this.getPatienHistoryData(obj);
				}, 300)
		})
	}

	// 另存为范例模板
	handleExampleTemplate = (record = {}) => {
		let { templateParams, treeSelectData } = this.state;
		treeSelectData = { ...treeSelectData, ...record };
		let defaultSelectedKeys = record && 'examListID' in record ? (record.examListID + '-' + record.examTempID) : '';
		if (defaultSelectedKeys) {
			treeSelectData.templateDesc = record?.examTempDesc || treeSelectData.templateDesc;
			treeSelectData.templateID = record?.examTemplateID || treeSelectData.templateID;
		}
		treeSelectData.wTempCataID = record?.examTempCataLogID || treeSelectData.wTempCataID || treeSelectData.ID;
		this.sampleTemplate && this.sampleTemplate.modifyVisible(true, templateParams, treeSelectData, defaultSelectedKeys);
	}

	//跳转到西药及其他
	goDoctorAdviceStepPage = () => {
		var params = {
			params: [{
				locID: this.state.userData.locID,
				hospID: this.state.userData.hospID,
				groupID: this.state.userData.groupID
			}]
		}
		$http.post('urlDeault', this, {
			code: '03050093',
			data: params,
			success: function (res) {
				if (res.errorCode == '0') {
					for (var i = 0; i < res.result.length; i++) {
						if (res.result[i].code === '03050038') {
							var { upDataComponentSource } = this.props;
							upDataComponentSource && upDataComponentSource(res.result[i]);
							return;
						}
					}
				}
			}
		});
	}

	// 跳转回引用界面
	handleGoToQuote = (defaultSelectedKeys) => {
		let { treeSelectData } = this.state;
		this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(true, treeSelectData, this.state.modalTemplateData, defaultSelectedKeys);
	}

	// 保存插入的病程记录
	handleSaveTheInsertedCourse = (selectionXml, templateID, templateData = {}) => {
		let { treeSelectData } = this.state;
		let obj = { ...templateData };
		obj.ID = templateID;
		this.SaveMedicalRecord(treeSelectData, obj, 'courseOfDisease', selectionXml);
	}

	// 发送验光单
	handleSend = async () => {
		try {
			let { modalRowData, treeSelectData } = this.state;
			let data = {
				params: [{
					wCatalogueID: treeSelectData?.ID || '', // 分组目录ID
					versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : '', // 病历模板ID
					patEMRRecordID: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
				}]
			}
			let res = await React.$asyncPost(this, '17020011', data);
			message.success(res?.errorMessage || '发送成功');
		} catch (error) {
			console.log(error)
		}
	}

	render() {
		let { historyAdmID, expandedKeys, selectedKeys, treeData, templateName, autoExpandParent, modalRowData, loadingTitle, spinLoading, isDeleteRecord, showValidateResult, isUnlocking } = this.state;

		let param = {
			isInsert: 'hidden',
			formView: 'Normal',
			isFont: true,
			isAllElection: true,
			isClearFormat: true,
			isSetTemplateSize: true,
			isSaveAnother: true,
			headerFooterEditable: 'noEditable',
			setChapter: 'show',
			isDelete: isDeleteRecord,
			printDocument: true,
			prTing: false,
			isBindingKnowledgeBase: true,
			showValidateResult,
			comments: true,
			isShear: true,
			isReload: false,
			self: false,
			original: false,
			isUnlocking, // 解锁按钮操作状态
			prCont: this.props.prCont && this.props.prCont === 'N' ? false : true,
			isBasicOperation: this.props.isBasicOperation ? this.props.isBasicOperation : false
		}

		const vCursor = this.state.isVResize ? 'col-resize' : 'default';
		const vColor = this.state.isVResize ? '#ddd' : 'rgba(240, 242, 245, 1)';
		return (
			<Spin tip={loadingTitle} spinning={spinLoading} delay={300} style={{ height: '100%' }}>
				<div style={{ height: this.props.clpHeader ? this.props.clpHeader : store.getState().tableHeight.y + 158 }} className="case-information-page">
					<div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', display: this.props.clpHeader ? 'none' : 'block' }}></div>
					<div style={{ width: '260px', height: 'calc(100% - 6px)', display: 'inline-block', overflow: 'hidden', paddingRight: '6px', position: 'relative' }}>
						<div style={{ textAlign: 'center', height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: '14px', background: '#fafafa', borderBottom: '1px solid #e8e8e8' }}>{this.setMessage('CaseInformationPageMRTemplate', 'descripts', '病历目录导航')}</div>
						<div style={{ height: 'calc(100% - 34px)', overflow: 'auto' }}>
							<div style={{ width: '100%', padding: '8px 8px 0' }}>
								<Input value={templateName} onChange={this.handleTemplateNameChange} placeholder={this.setMessage('CaseInformationPageTemplate_name_query', 'descripts', '请输入模板名称查询')} />
							</div>
							<Tree showIcon
								autoExpandParent={autoExpandParent}
								onExpand={this.onExpand}
								expandedKeys={expandedKeys}
								onSelect={this.onSelect}
								selectedKeys={selectedKeys}
								onDoubleClick={this.dblclickTreeNodes}>
								{this.renderTreeNodes(treeData)}
							</Tree>
						</div>
						<div style={{ position: 'absolute', right: '0', top: '0', width: '6px', background: 'rgba(240, 242, 245, 1)', height: '100%' }}></div>
					</div>
					<div style={{ width: 'calc(100% - 260px)', position: 'relative', height: 'calc(100% - 6px)', overflow: 'hidden', display: 'inline-block' }}
						onMouseUp={this.stopResize} onMouseLeave={this.stopResize}
					>
						<div id='v_resize_container' style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, height: '100%' }} onMouseMove={this.vResizeOver}>
							<div id='h_resize_container' style={{ width: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === 'N' ? '100%' : this.state.vNum, cursor: vCursor, height: '100%', float: 'left' }} onMouseMove={this.hResizeOver}>
								<div style={{ height: '100%' }}>
									<ElectronicCaseTemplate
										param={param}
										pasteRemoveSpaces="N"
										onRef={this.handleCaseTemplateRef}
										handleSend={this.handleSend}
										handleSave={this.handleSave}
										handleDelete={this.deletePatientHistory}
										getKnowledgeBaseTreeData={this.getChildKnowledgeBaseTreeData}
										handleReload={this.handleOk}
										handleExampleTemplate={this.handleExampleTemplate} // 另存为范例模板
										handleOnReload={modalRowData && modalRowData.ID ? () => this.getPatienHistoryData(modalRowData) : ''}
										editorID={this.props.editorID ? this.props.editorID : 'CIPWriterControl'}
										handleSaveTheInsertedCourse={this.handleSaveTheInsertedCourse} // 保存插入的病程记录
										updateMedicalRecordLockStatus={() => this.updateMedicalRecordLockStatus(modalRowData && modalRowData.patEMRRecordID ? modalRowData.patEMRRecordID : eMRRecordID, 'forceUnlock')}
									/>
								</div>
							</div>
							<div style={{ left: this.state.vNum, backgroundColor: vColor, display: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === 'N' ? 'none' : 'block' }} draggable={false} onMouseDown={this.vResizeDown} className='v-resize' />
							<div style={{ marginLeft: this.state.vNum + 6, cursor: vCursor, height: '100%', display: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === 'N' ? 'none' : 'block' }}>
								<CaseInformationPageTabs
									historyAdmID={historyAdmID}
									handleQuote={this.handleQuote} setKnowledgeBaseXMl={this.setKnowledgeBaseXMl} onRef={this.handleCaseInformationRef}
									modalRowData={this.state.modalRowData} treeSelectData={this.state.treeSelectData} compileVNum={this.compileVNum}
									knowledgeBaseAssignment={this.knowledgeBaseAssignment}
								/>
							</div>
						</div>
					</div>

					{/* 另存为范例病例 */}
					<AddSampleTemplate handleGoToQuote={this.handleGoToQuote} onRef={ref => this.sampleTemplate = ref} />

					{/* 病历模板选择 */}
					<MedicalRecordTemplateSelection handleModify={this.handleExampleTemplate} handleOk={this.handleOk} onRef={ref => this.medicalRecordTemplate = ref} />

					<ColumnAuthoritysModel
						clientWidth="800px"
						compontName="CaseInformationPage"
						configType="C"
						onRef={this.onMainColumnRef}
						reloadData={this.getChineseAndEnglishData}
					/>
				</div>
			</Spin>
		)
	}
};

export default CaseInformationPage;